package com.ruoyi.file.service.impl;

import com.ruoyi.file.bean.FileUploadResult;
import com.ruoyi.file.utils.FileUploadUtils;
import com.ruoyi.file.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 本地文件存储
 *
 * @author william.zhao & zhao xiang.
 * @version 1.0
 * @since jdk-17.0.2
 * @date 2023/05/05
 */
@Service
public class LocalSysFileServiceImpl extends AbstractFileService {
    /** 资源映射路径 前缀。 */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /** 域名或本机访问地址。 */
    @Value("${file.domain}")
    public String domain;

    /** 上传文件存储在本地的根路径。 */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 本地文件上传接口。
     *
     * @param file 上传的文件。
     * @return the upload result, result[0] means the url, result[1] means the file path.
     * @throws Exception
     */
    @Override
    public FileUploadResult uploadFile(MultipartFile file) throws Exception {
        String name = FileUploadUtils.upload(localFilePath, file);
        String url = domain + localFilePrefix + name;
        String fileMD5 = Md5Utils.getFileMD5(file.getInputStream());

        FileUploadResult uploadResult = new FileUploadResult();
        uploadResult.setFileName(name);
        uploadResult.setUrl(url);
        uploadResult.setFileMD5(fileMD5);
        return uploadResult;
    }

    /**
     * remove file by file path in server.
     *
     * @param filePath the file path in server, the filePath likes: 2023/07/06/blob_20230706112107A003.png
     * @return success or fail.
     */
    @Override
    public String removeFile(String filePath) {
        String flag = FileUploadUtils.remove(localFilePath, filePath);
        return flag;
    }

}
